<template>
  <el-row class="dataConnection" @click="onMenuClose">
    <!-- 侧边栏 -->
    <el-col :span="3" class="aside">
      <div class="title">
        <span>数据连接</span>

        <el-popover
            placement="bottom-start"
            title=""
            :width="122"
            trigger="click"
            content="this is content, this is content, this is content"
        >
            <div>
              <el-button class="menu_button" text='plain' @click="createNewCon">
                <img slot="prepend" alt="" class="button_group_icon" src="@/assets/images/rxtree_child_focus.png">
                <span style="width: 7em;text-align: left">新建连接</span>
              </el-button>
              <el-button class="menu_button" text='plain' @click="openInputDialog('1',)">
                <img slot="prepend" alt="" src="@/assets/images/rxtree_parent_focus.png">
                <span style="width: 7em;text-align: left">新建文件夹</span>
              </el-button>

            </div><!--v-show="addMenu"-->
          <template #reference>
<!--            <el-button class="m-2">Click to activate</el-button>-->
            <img src="@/assets/images/server_add.png" style="width:30px;height:30px;cursor:pointer;"
                 @click="addMenu = !addMenu"/>
          </template>
        </el-popover>
      </div>
      <div class="search">
        <el-select
            v-model="options[0].value"
            class="m-2 select"
            placeholder="Select"
        >
          <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
        <el-input
            class="input"
        />
      </div>
      <el-tree
          ref="treeRef"
          :data="groupData"
          :props="defaultProps"
          highlight-current
          node-key="nodeId"
          @node-contextmenu="onContextMenu"
          @node-click="treeNodeClick"
      >
        <template #default="{ node, data }">
                <span class="custom-tree-node">
                  <span class="tree_nodei_icon">
                    <img v-if="data.nodeType == 1" alt="" class="tree_nodei_img"
                         src="@/assets/images/rxtree_parent_focus.png">
                    <img v-else alt="" class="tree_nodei_img" src="@/assets/images/rxtree_child_focus.png">
                  </span>
                  <span>{{ node.label }}</span>
                </span>
        </template>
      </el-tree>

    </el-col>
    <!-- 内容 -->
    <el-col
        :span="21"
        class="main"
    >
      <el-empty
          v-show="!selectedContent"
          class="empty"
          description="请选择数据连接"
      />
      <ConnContent
          v-show="selectedContent"
          :dsId="dsNO"
          :groupId="menuConfig.data.nodeType == 1 ? menuConfig.data.nodeId :'' "
          class="empty"
          @cancel="cancel"
          @treeFresh="selectGroups"

      />
    </el-col>
    <!-- 新建文件夹弹窗 -->
    <el-dialog
        v-model="folderDia"
        :close-on-click-modal="false"
        draggable
        title="新建文件夹"
        width="300"
    >
      <el-input v-model="folderName"/>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="folderDia = false;folderName = ''">取消</el-button>
          <el-button
              type="primary"
              @click="insertGroup"
          >确认</el-button>
        </span>
      </template>
    </el-dialog>

    <div v-show="menuShow" id="option-button-group" :style="menuStyle">
      <div v-if="menuConfig.data.nodeType == 1">
        <el-button class="menu_button" text='plain' @click="openInputDialog('1',true)">
          <img slot="prepend" alt="" src="@/assets/images/rxtree_parent_focus.png">
          <span style="width: 5em;text-align: left">新建文件夹</span>
        </el-button>
        <el-button class="menu_button" text='plain' @click="createNewCon(true)">
          <img slot="prepend" alt="" class="button_group_icon" src="@/assets/images/rxtree_child_focus.png">
          <span style="width: 5em;text-align: left">新建连接</span>
        </el-button>
      </div>

      <el-button class="menu_button" text='plain' @click="openInputDialog('2')">
        <img slot="prepend" alt="" class="button_group_icon" src="@/assets/images/edit_blue.png">
        <span style="width: 5em;text-align: left">重命名</span>
      </el-button>
      <div style="width: 100%;border: 1px solid #d8d8d8;"></div>
      <el-button class="menu_button" text='plain' @click="moveNode('1')">
        <img slot="prepend" alt="" class="button_group_icon" src="@/assets/images/moveup_blue.png">
        <span style="width: 5em;text-align: left">上移</span>
      </el-button>
      <el-button class="menu_button" text='plain' @click="moveNode('2')">
        <img slot="prepend" alt="" class="button_group_icon" src="@/assets/images/movedown_blue.png">
        <span style="width: 5em;text-align: left">下移</span>
      </el-button>
      <div style="width: 100%;border: 1px solid #d8d8d8;"></div>
      <el-button class="menu_button" text='plain' @click="deleteNode">
        <img slot="prepend" alt="" class="button_group_icon" src="@/assets/images/delete_blue.png">
        <span style="width: 5em;text-align: left">删除</span>
      </el-button>
    </div>


  </el-row>
</template>

<script setup>
import {computed, onMounted, provide, reactive, ref, toRefs} from "vue";
import ConnContent from '@/views/scene/ConnContent';
import {deleteDsConnect, getExistDataConnect, moveDSNodeOrder, saveDSNodeName} from '@/services/dataConnection'
import {ElMessage} from 'element-plus';

const data = reactive({
  groupData: []
})

const treeRef = ref()

const menuConfig = reactive({
  x: '0',
  y: '0',
  data: {}
})
const menuShow = ref(false)
const {groupData} = toRefs(data);

const defaultProps = {
  label: 'nodeName',
  children: 'children',
}

const defaultProps1 = {
  label: 'nodeName',
  children: 'dsInfos',
}

const props = {
  label: "text",
  children: "children",
}

const options = [
  {label: '名称', value: 'name'},
  {label: '类型', value: 'type'}
]
const serviceRequestData = ref({})//重命名，新建的参数
const selectedContent = ref(false); // 是否选中内容
const addMenu = ref(false); // 展示添加菜单

const folderDia = ref(false); // 展示新建文件夹弹窗
const folderName = ref('');  // 新建文件夹的名字

const connDia = ref(false); // 展示新建数据连接弹窗
const dsType = ref('MYSQL'); // 新建连接的类型，默认为MYSQL
const dsNO = ref(''); // 数据源连接id
provide('dsNO', dsNO);
provide('dsType', dsType);

const menuStyle = computed(() => {
  const res = {
    left: `${menuConfig.x}px`,
    top: `${menuConfig.y}px`,
    'z-index': 9999,
    position: 'fixed',
    width: '100px',
    border: '1px solid #d8d8d8',
    'background-color': '#fff'
  }
  return res;
});

//左侧树
async function selectGroups() {
  // 获取后端结果
  const result = await getExistDataConnect({groupType: '1'});
  if (!result?.respStatus) {
    ElMessage({
      message: '请求出错：' + result?.respMessage,
      type: 'error'
    })
  } else {
    data.groupData = result?.respData;
  }
  // if (result?.respStatus && !result.respStatus) return;
}

//打开dialog,并整理参数
async function openInputDialog(operationType, creatFromFolder) {
  folderDia.value = true
  menuShow.value = false
  let data = {
    editType: operationType,
    isLeaf: menuConfig.data.nodeType == 1 ? '0' : '1'
  }
  if (operationType == '2' || creatFromFolder) {
    //在文件夹中新建文件夹
    data.nodeID = menuConfig.data.nodeId
  }
  serviceRequestData.value = data
}

onMounted(() => {
  selectGroups();
})

// 操作Input的dialog
async function insertGroup() {
  if (!folderName.value) return ElMessage({
    message: '请输入名称',
    type: 'error',
  });
  serviceRequestData.value.editName = folderName.value
  const res = await saveDSNodeName(serviceRequestData.value)
  if (res?.respStatus) {
    ElMessage({
      message: '操作成功',
      type: 'success'
    })
    await selectGroups()
  }
  folderName.value = ''
  folderDia.value = false; // 关闭新建文件夹弹窗
  addMenu.value = false; // 关闭添加菜单
}

//删除node
async function deleteNode() {
  if (menuConfig.data.nodeType == '1' && treeRef.value.getNode(menuConfig.data.nodeId).childNodes.length !== 0) {
    //如果是文件夹且文件夹下有节点
    ElMessage({
      message: '文件夹不为空,无法删除',
      type: 'error'
    })
    return
  }
  const data = {
    nodeCode: menuConfig.data.nodeId,
    nodeType: menuConfig.data.nodeType == '1' ? '0' : '1'
  }
  const res = await deleteDsConnect(data)
  if (res?.respStatus) {
    ElMessage({
      message: res?.respMessage,
      type: 'success'
    })
    selectGroups()
    selectedContent.value = false
  } else {
    ElMessage({
      message: res?.respMessage,
      type: 'error'
    })
  }
  menuShow.value = false
}

//移动节点
async function moveNode(moveType) {
  const data = {
    moveType: moveType,
    moveID: menuConfig.data.nodeId,
    moveGroup: menuConfig.data.parentId,
    nodeType: menuConfig.data.nodeType == '1' ? '0' : '1'
  }
  const res = await moveDSNodeOrder(data)
  if (res?.respStatus) {
    ElMessage({
      message: res?.respMessage,
      type: 'success'
    })
    await selectGroups()
  } else {
    ElMessage({
      message: res?.respMessage || '移动接口错误',
      type: 'success'
    })
  }
  menuShow.value = false
}

//新建连接
function createNewCon(isFormGroup) {
  selectedContent.value = true;
  addMenu.value = false
  dsNO.value = null
  if (isFormGroup) {
    menuShow.value = false
  }
}

function cancel() {
  selectedContent.value = false;
}

//节点点击事件
function treeNodeClick(curNode, node, treeNode, event) {
  if (curNode.nodeType == 2) {
    dsNO.value = curNode.nodeId
    selectedContent.value = true
    console.log(event)
    // event.target.classList.add('actonTreeNode')
  }
}

//onContextMenu右键点击事件
function onContextMenu(event, curData, node) {
  console.log(curData, node)
  menuShow.value = false
  menuConfig.x = event.x   // 让右键菜单出现在鼠标右键的位置
  menuConfig.y = event.y
  menuConfig.data = curData
  treeRef.value.setCurrentKey(curData.nodeId)
  menuShow.value = true
}

//点击  菜单的  其他位置，隐藏菜单
function onMenuClose(event) {
  const currentCli = document.getElementById("option-button-group");
  // const addIconShow = document.getElementsByClassName('addMenu')[0]
  // console.log('addIconShow', addIconShow)
  if (currentCli) {
    if (!currentCli.contains(event.target)) { //点击到了id为option-button-group以外的区域，就隐藏菜单
      menuShow.value = false
    }
  }
}
</script>

<style lang="scss" scoped>

.dataConnection {
  width: 100%;
  height: 100%;


  .aside {
    border-right: solid 1px #197bff;
    padding-right: 5px;

    .title {
      padding: 15px 5px;
    }

    ::v-deep .el-input__wrapper {
      border-radius: 0;
      border-right: 0;
    }

    .addMenu {
      width: 120px;
      border: solid 1px #dedede;
      background-color: #fff;
      position: absolute;
      z-index: 999;
      font-size: 14px;
    }

    .verCenter {
      cursor: pointer;
      display: flex;
      align-items: center;
      padding: 10px 5px;

      &:hover {
        color: blue;
        background-color: skyblue;
      }
    }

  }

  .main {
    height: calc(100% - 40px);
    overflow: hidden;
    position: relative;

    .empty {
      width: 100%;
      height: 100%;
    }
  }

  .title {
    display: flex;
    align-items: center;
    justify-content: space-between;
    position: relative;

    .left {
      display: flex;
      align-items: center;
    }
  }

  .icon {
    cursor: pointer;
    color: #808080;
    padding: 5px;

    &:hover {
      color: skyblue;
    }
  }

  .search {
    display: flex;
    padding-left:10px;

    .select {
      width: 40%;
    }

    .input {
      width: 60%;
    }
  }

  .custom-tree-node {

    .tree_nodei_icon {
      margin-right: 6px;
    }

    .tree_nodei_img {
      vertical-align: middle;
    }
  }
}

.menu_button {
  width: 100%;
  margin-left: 0;
  font-size: 14px;
  border-radius: 0;

  .button_group_icon {
    width: 18px;
  }
}
</style>
<style>

</style>